const http = require("http");
const fs = require("fs");
const path = require("path");

var userList = [];

function getData(str) {
    var arr = str.split("&");
    var obj = {};
    for (var i = 0; i < arr.length; i++) {
        var childArr = arr[i].split("=");
        obj[childArr[0]] = childArr[1];
    }
    return obj;
}

http.createServer((req, res) => {
    var urlObj = new URL(req.url, "http://localhost:8081/");
    var pathName = urlObj.pathname;
    if (pathName == "/") {
        var filePath = path.join(__dirname, "/post.html");
        var fileContent = fs.readFileSync(filePath);
        res.writeHead(200, { "Content-Type": "text/html;charset=utf-8" });
        res.write(fileContent);
        res.end();
    } else if (pathName == "/save") {
        // 做表单数据的接收，存储到userList中
        //提交表单需要用req接收数据的方法

        // console.log(req.headers);
        // console.log(req);
        var str = "";
        req.on("data", (chunk) => {
            str += chunk;
        });
        req.on("end", () => {
            // console.log(str);
            var postObj = getData(str);
            userList.push(postObj);
            res.end("submit success");
        });
    } else if (pathName == "/list") {
        // 响应list.html页面到浏览器
        var filePath = path.join(__dirname, "/list.html");
        var fileContent = fs.readFileSync(filePath);
        res.writeHead(200, { "Content-Type": "text/html;charset=utf-8" });
        res.write(fileContent);
        res.end();
    } else if (pathName == "/getlist") {
        // 响应userList数据到客户端
        var userStr = JSON.stringify(userList);
        res.writeHead(200, { "Content-Type": "text/plain" });
        res.end(userStr);
    } else if (pathName == "/del") {
        // 删除数据过程，接收请求、del?deluser=zhangsan
        // 根据username从userList里面将该条数据删除
        var delUser = urlObj.searchParams.get("deluser");
        console.log(delUser);
        for (var i = 0; i < userList.length; i++) {
            if (userList[i]["username"] == delUser) {
                userList.splice(i, 1);
                res.end("delete success");
                return;
            }
        }
    }
}).listen(8081);
console.log("listening on port 8081");
